package cn.xuqiudong.duoduo.helper;

import cn.xuqiudong.common.util.date.DateTimeUtils;
import cn.xuqiudong.duoduo.constant.CommonConstant;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;

import java.text.ParseException;
import java.time.LocalDate;
import java.time.Period;
import java.util.Date;

/**
 * 描述: 年龄显示
 * @author Vic.xu
 * @since 2024-03-25 10:49
 */
public class AgeHelper {

    public static final LocalDate BIRTH_DATE = DateTimeUtils.date2LocalDate(CommonConstant.birthday);

    public static final String DATE_PATTERN = "yyyy-MM-dd";

    /**
     * 显示年龄的阈值
     */
    private static final int MIN_SHOW_AGE = 9;

    public static String showDate(Date date) {
        return DateFormatUtils.format(date, DATE_PATTERN);
    }


    /**
     * 展示age
     * <p>
     *     1. 10岁以上直接显示x岁
     *     2. x岁x个月 （x岁）
     *     3. x个月x天 (x月）
     *     4. x天
     * </p>
     */
    public static String showAge(Date endDate) {
        Period p = Period.between(DateTimeUtils.date2LocalDate(endDate), BIRTH_DATE);
        int year = Math.abs(p.getYears());
        int month = Math.abs(p.getMonths());
        int day = Math.abs(p.getDays());
        System.out.println(year + " " + month + " " + day);
        if (year > MIN_SHOW_AGE) {
            return year + "岁";
        }

        String result = "";
        if (year > 0) {
            result = year + "岁";
            if (month > 0) {
                result += month + "个月";
            }
            return result;
        } else {
            if (month > 0) {
                result = month + "个月";
                if (day > 0) {
                    result += day + "天";
                }
                return result;
            }
        }

        return day + "天";
    }

    public static void main(String[] args) throws ParseException {


        System.err.println(showAge(new Date()));
        System.err.println(showAge(toDate("2022-01-24")));
        System.err.println(showAge(toDate("2022-03-21")));
        System.err.println(showAge(toDate("2024-01-28")));
    }

    public static Date toDate(String date) throws ParseException {
        return DateUtils.parseDate(date, "yyyy-MM-dd");
    }

}
